import {
	baseUrl
} from "./tool.js"

const BASE_URL = baseUrl + "/index.php/api"

// 全局请求
const request = (url, params, method = "GET") => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '正在加载...',
			mask: true
		});
		uni.request({
			url: BASE_URL + url,
			method: method,
			timeout: 1000 * 5,
			data: params,
			success(res) {
				uni.hideLoading();
				let code = res.data.code
				if (code === 1) {
					resolve(res.data)
				} else if (res.statusCode === 404) {
					uni.showToast({
						title: "请求服务器失败",
						mask: true,
						icon: "none",
						duration: 3000
					})
				} else {
					uni.showToast({
						title: res.data.msg,
						mask: true,
						icon: "none",
						duration: 3000
					})
				}
			},
			fail(err) {
				console.log(err)
				uni.hideLoading();
				if (err.errMsg === "request:fail timeout") {
					uni.showToast({
						title: "请求超时",
						icon: "none",
						mask: true,
						duration: 3000
					})
				} else {
					uni.showToast({
						title: "请求服务器失败",
						icon: "none",
						mask: true,
						duration: 3000
					})
				}
				reject(err);
			},
		});
	});
};

export default request